﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;

namespace Test.Common
{
   public  class ConfigHelper
    {

        /// <summary>
        /// 默认到AppSetting找，没找到反射查找同名字段，再没有返回空
        /// </summary>
        public static string GetConfigValue(string key, string defaultVal = "")
        {
            //默认从AppSetting中提取
            var result = ConfigurationManager.AppSettings[key];

            //获取反射变量的值
            var confType = typeof(CommonConf);
            if (string.IsNullOrWhiteSpace(result))
            {
                var refField = confType
                        .GetFields(BindingFlags.Public | BindingFlags.Static)
                        .FirstOrDefault(f => f.Name.ToLower() == key.ToLower());

                if (refField != null)
                {
                    result = refField.GetValue(null).ToString();
                }
            }

            //如果还是没有，返回默认值
            return result ?? defaultVal;
        }
    }
}
